<?php

class PlaylistController extends Zend_Controller_Action
{

    /**
     * Neprihlaseny uzivatel se presmeruje na login
     *
     * fm jmeno se ulozi do session
     */
    public function init()
    {
        if ($this->_getParam('name'))
        {
            $session = new Zend_Session_Namespace('fm');
            $session->fm = $this->_getParam('name');
        }

        if (!LastFM_User::isActiveUser() && $this->_request->getActionName() != "play")
        {
            $this->_helper->redirector->gotoSimple('login', 'user');
        }
    }

    /**
     *
     */
    public function indexAction()
    {
        if (!Zend_Auth::getInstance()->hasIdentity())
        {
            // neprihlaseny uzivatle rovnou vytvari playlist
            //$this->_forward('create-playlist');
        }

        $fmUser = LastFM_User::getActiveUser();

        $this->view->user_info = $fmUser->getInfo();
        $this->view->artists = $fmUser->getTopArtists();
        $this->view->top_tracks = $fmUser->getTopTracks();
        $this->view->loved_tracks = $fmUser->getLovedTracks();
    }

    /**
     *
     */
    public function createPlaylistAction()
    {
        $fmUser = LastFM_User::getActiveUser();

        $this->view->user_info = $fmUser->getInfo();
        $this->view->artists = $fmUser->getTopArtists();
        $this->view->top_tracks = $fmUser->getTopTracks();
        $this->view->loved_tracks = $fmUser->getLovedTracks();

        $form = new Form_Playlist();
        $form->setAction($this->_helper->url->simple('party-playlist'));

        if ($this->_getParam('error'))
        {
            $form->isValid($this->_helper->PostForm->retrieve());
        }

        $this->view->form = $form;
        $this->view->headTitle('Playlist');
    }

    public function partyPlaylistGeneratorAction()
    {
        //generování playlistu
        $generator = new Playlist_Generator_Party();
        $generator->setUsers($_SESSION["playlist_friends"]);
        $generator->setLimit($_SESSION["playlist_limit"]);
        $generator->setArtists($_SESSION["playlist_artists"]);
        $generator->setTracks($_SESSION["playlist_songs"]);

        $playlist = $generator->getPlaylist();
        $outputType = $_SESSION["playlist_outputtype"];

        $this->view->count = count($_SESSION["playlist_friends"]);
        $this->view->friendlist = $_SESSION["playlist_friends"];
        $this->view->playlist = $playlist;
        $this->view->headTitle($playlist->getName());

        if ($outputType == "grooveshark")
        {
            $session = new Zend_Session_Namespace('playlist');
            $session->unsetAll();
            $session->playlist_name = 'Party Playlist';
            $songIDs = $playlist->getSongIDs();
            $session->songIDs = $songIDs;

            $this->view->songIDs = $songIDs;
        }

        if ($outputType == "html" || $outputType == "tinysong" || $outputType == "grooveshark")
        {
            $this->render($outputType . "-party-playlist");
        }
        elseif ($outputType == "xml")
        {
            //potřeba doplnit a zkontrolovat zda to bude s ajaxem fachat...
            //pro vystup XML - vsechny promenny, ktere jsou elementy, atributy jsou nazvany
            //pocatecnim prefixem _x

            $xml = $dom->saveXML();
            $this->_helper->layout->disableLayout();
            $this->_helper->viewRenderer->setNoRender();
            $this->_response->setHeader("Content-Disposition", "attachment; filename=" . $form->getValue("playlist_name") . ".xml");
            $this->_response->setHeader('Content-type', 'text/xml', 'true');
            $this->_response->setBody($xml);
        }

        $this->getHelper('layout')->disableLayout();
    }

    /**
     *
     */
    public function partyPlaylistAction()
    {
        $fmUser = LastFM_User::getActiveUser();
        $form = new Form_Playlist();

        if ($form->isValid($this->_request->getPost()))
        {
            $friend_names = $form->getValue('friends');
            $friends = array();

            foreach ($friend_names as $friend)
            {
                $friends[] = new LastFM_User($friend);
            }

            $_SESSION["playlist_friends"] = $friends;
            $_SESSION["playlist_limit"] = $form->getValue('limit');
            $_SESSION["playlist_artists"] = $form->getValue('artists');

            //získání skladeb z text area
            $allTracks = $form->getValue('add_songs');
            $preferedTracks = array();
            if ($allTracks != null)
            {
                $ar = explode("\n", $allTracks);
                foreach ($ar as $artistAndTrack)
                {
                    $artistName = substr($artistAndTrack, 0, strrpos($artistAndTrack, "-"));
                    $songName = substr($artistAndTrack, strrpos($artistAndTrack, "-") + 1);
                    $preferedTracks[] = new Track($songName, $artistName);
                }
            }

            $_SESSION["playlist_songs"] = $preferedTracks;
            $outputType = $form->getValue('outputType');
            $_SESSION["playlist_outputtype"] = $outputType;

            $this->render("party-playlist-ajax");
        }
        else
        {
            $this->_helper->PostForm->save();
            $this->_helper->redirector->gotoSimple('create-playlist', null, null, array('error' => 1));
        }
    }

    /**
     * AJAX loading
     */
    public function favouritePlaylistAction()
    {
        $name = $this->_getParam('name');

        if (empty($name))
        {
            $user = LastFM_User::getActiveUser();

            $name = $user->getName();
        }

        $this->view->name = $name;
        $this->view->limit = (int) $this->_getParam('limit', 30);


        $this->view->headTitle($name);
        $this->view->headTitle('Favourite Tracks');
    }

    public function savePlaylistAction()
    {
        $user = User::getActiveUser();

        $session = new Zend_Session_Namespace('playlist');

        $playlist = new Playlist($this->view->translate('New Playlist'), (array) $session->songIDs);
        $id = $playlist->save($user);

        $this->_helper->redirector->gotoSimpleAndExit('edit-playlist', 'playlist', null, array('id' => $id));
    }

    public function deletePlaylistAction()
    {
        $db = Zend_Db_Table::getDefaultAdapter();

        $id = (int) $this->_getParam('id');

        $db->delete('playlist', $db->quoteInto('id = ?', $id) . ' AND ' . $db->quoteInto('user_id = ?', User::getActiveUser()->getID()));

        $this->_helper->redirector->gotoSimple('my-playlist');
    }

    public function xmlPlaylistAction()
    {
        $id = (int) $this->_getParam('id');

        $playlist = Playlist::load($id);

        $xml_playlist = new Playlist_Xml($playlist);

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->_response->setHeader("Content-Disposition", "attachment; filename=" . $playlist->getName() . ".xspf");
        $this->_response->setHeader('Content-Type', 'application/xspf+xml;charset=UTF-8', 'true');
        $this->_response->setBody($xml_playlist->getXml());
    }

    public function friendsAction()
    {
        $user = LastFM_User::getActiveUser();

        $this->view->friends = $user->getFriends();
    }

    /**
     * 
     */
    public function favouritePlaylistGeneratorAction()
    {
        $name = $this->_getParam('name');

        if (empty($name))
        {
            $user = LastFM_User::getActiveUser();

            $name = $user->getName();
        }
        else
        {
            $user = new LastFM_User($name);
        }



        $session = new Zend_Session_Namespace('playlist');
        $session->unsetAll();

        $generator = new Playlist_Generator_Favourite();
        $generator->setLimit((int) $this->_getParam('limit', 30));
        $generator->setName($user->getName() . ' ' . $this->view->translate('Favourite Tracks'));
        $generator->setUser($user);

        $playlist = $generator->getPlaylist();
        $songIDs = $playlist->getSongIDs();

        $session->songIDs = $songIDs;

        $this->view->playlist_name = $playlist->getName();
        $this->view->playlist = $playlist;
        $this->view->songIDs = $songIDs;
        $this->view->autoplay = $user->autoplay;

        $this->getHelper('layout')->disableLayout();
    }

    /**
     * Moznost vyhledat a prehrat vlastni song
     *
     */
    public function customTrackAction()
    {
        if ($this->_request->isPost())
        {
            $this->_helper->redirector->gotoSimple('play-track', null, null, array('track-name' => urlencode($this->_getParam('artist') . ' - ' . $this->_getParam('song'))));
        }

        $this->view->artist = $this->_getParam('artist');
        $this->view->song = $this->_getParam('song');


        $this->view->headTitle('Custom Track');
    }

    public function playSongAction()
    {
        $this->view->songID = $this->_getParam('id');

        $this->getHelper('layout')->disableLayout();
    }

    /**
     * Zjisti ID pisnicky z grooveshark DB a preda ho flash widgetu ve view
     *
     */
    public function playTrackAction()
    {
        $name = $this->_getParam('track-name');

        $name = str_replace('+', ' ', $name);
        $a = explode('-', $name);


        $artist = urldecode(trim($a[0]));

        unset($a[0]);

        $song_name = urldecode(trim(implode('-', $a)));

        $track = DbTrack::loadTrack(new Track($song_name, $artist));

        if (is_null($track))
        {
            $this->view->failed = true;
            $this->view->headTitle('Track not found');
        }
        else
        {


            $user = LastFM_User::getActiveUser();
            $this->view->autoplay = $user->autoplay;


            $this->view->songID = $track->getID();
            $this->view->song_name = $track->getSong();
            $this->view->artist = $track->artist_name;
            $this->view->album_name = $track->getAlbum();
            $this->view->url = $track->getUrl();

            $this->view->headTitle($track->getName());
        }
    }

    public function myPlaylistAction()
    {
        $db = Zend_Db_Table::getDefaultAdapter();
        $user = User::getActiveUser();
        $fm = LastFM::getInstance();




        $playlists = new DbPlaylists();

        $this->view->playlists = $playlists->fetchAll($db->quoteInto('user_id = ?', $user->getID()));

        $fm_playlists = $fm->user_getPlaylists(array("user" => LastFM_User::getActiveUser()->getName()));
        $this->view->fm_playlists = $fm_playlists;
    }

    public function editPlaylistAction()
    {
        $db = Zend_Db_Table::getDefaultAdapter();

        $id = (int) $this->_getParam('id');

        if (empty($id))
        {
            $user = User::getActiveUser();
            $db->insert('playlist', array('user_id' => $user->getID(), 'name' => $this->_getParam('name', $this->view->translate('New Playlist')), 'date_created' => new Zend_Db_Expr('NOW()')));

            $id = $db->lastInsertId();

            $this->_helper->redirector->gotoSimpleAndExit('edit-playlist', null, null, array('id' => $id));
        }

        if ($this->_request->isPost())
        {
            $db->update('playlist', array('name' => $this->_getParam('name')), $db->quoteInto('id = ?', $id));
            die;
        }



        $select = $db->select()->from('playlist');
        $select->where('id = ?', $id);

        $this->view->info = $db->fetchRow($select);


        $select = $db->select();
        $select->from('playlist_has_track', array());
        $select->join('tracks', 'track_id = tracks.id');
        $select->where('playlist_id = ?', $id);
        $select->order('custom_order');

        $tracks = $db->fetchAll($select);

        $this->view->tracks = $tracks;
        $this->view->playlist_id = $id;
    }

    public function playTagsAction()
    {
        $db = Zend_Db_Table::getDefaultAdapter();


        $id = (int) $this->_getParam('id');



        $select = $db->select()->from('playlist');
        $select->where('id = ?', $id);

        $this->view->info = $db->fetchRow($select);


        $select = $db->select();
        $select->from('playlist_has_track', array());
        $select->join('tracks', 'track_id = tracks.id');
        $select->where('playlist_id = ?', $id);
        $select->order('custom_order');

        $tracks = $db->fetchAll($select);

        $tags = array();

        foreach ($tracks as $track)
        {

            $my_track = new Track($track["song"], $track["artist_name"]);

            $xml_tags = $my_track->getTopTags();

            foreach ($xml_tags->toptags->tag as $tag)
            {
                $tag_name = (string) $tag->name;



                if (!isset($tags[$tag_name]))
                {
                    $tags[$tag_name] = 0;
                }

                $tags[$tag_name] += (int) $tag->count;
            }
        }

        arsort($tags);

        $this->view->tracks = $tracks;
        $this->view->playlist_id = $id;
    }

    public function publishAction()
    {
        $id = (int) $this->_getParam('id');


        $playlist = Playlist::load($id);
        $playlist->publish(User::getActiveUser());
    }

    public function playAction()
    {
        $id = (int) $this->_getParam('id');
        $db = Zend_Db_Table::getDefaultAdapter();

        if ($this->_getParam('fm'))
        {

            $playlist = Playlist::fetch($id);
        }
        else
        {
            $playlist = Playlist::load($id);
        }




        $this->view->songIDs = $playlist->getSongIDs();

        $this->view->playlist_title = $playlist->getName();

        if (LastFM_User::isActiveUser())
        {
            $user = LastFM_User::getActiveUser();
            $this->view->autoplay = $user->autoplay;
        }
        else
        {
            $this->view->autoplay = true;
        }
    }

    public function searchAction()
    {
        $cache = $this->_helper->cache->getCache('tinysong');

        $name = $this->_getParam('q', "Girl+Talk+Ask+About+Me");

        $cache_id = md5($name);

        $results = $cache->load($cache_id);

        if (!$results)
        {
            $results = TinySong::search($name);

            foreach ($results as $data)
            {
                DbTrack::insertTrack($data);
            }

            $cache->save($results, $cache_id);
        }

        $json = Zend_Json::encode($results);


        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->_response->setHeader('Content-Type', 'application-json;charset=UTF-8', 'true');
        $this->_response->setBody($json);
    }

    /**
     * @todo zabranit ostatnim uzivatelum editovat cizi playlist
     */
    public function updatePlaylistAction()
    {
        $id = (int) $this->_getParam('id');

        $db = Zend_Db_Table::getDefaultAdapter();

        $db->beginTransaction();

        $db->delete('playlist_has_track', $db->quoteInto('playlist_id = ?', $id));


        $songs = (array) $this->_getParam('songs');

        $set = array();
        $set['playlist_id'] = $id;

        foreach ($songs as $order => $track_id)
        {
            $set['custom_order'] = $order;
            $set['track_id'] = $track_id;
            $db->insert('playlist_has_track', $set);
        }

        $db->commit();

        die;

        $json = Zend_Json::decode($songs);

        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender();
        $this->_response->setHeader('Content-Type', 'application-json;charset=UTF-8', 'true');
        $this->_response->setBody($json);
    }

}
